package com.saicmotor.springboot_demo.service.impl;

import com.saicmotor.springboot_demo.model.json_pojo.JsonResult;
import com.saicmotor.springboot_demo.service.ExceptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class ExceptionServiceImpl implements ExceptionService {

    @Autowired
    JsonResult jsonResult;

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.info("参数校验异常: "+e.getMessage(),e);
        return jsonResult.msg(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonResult handleConstraintViolationException(ConstraintViolationException e){
        log.info("参数校验异常: "+e.getMessage(),e);

        StringBuffer sb = new StringBuffer();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        violations.forEach(violation->{
            sb.append(violation.getMessage()).append("\n");
        });
        return jsonResult.msg(sb.toString());
    }
}

